package com.ztfgroup.supervise.intercept;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hszsd.weixin.api.SnsAPI;
import com.hszsd.weixin.bean.ScopeEnum;
import com.hszsd.weixin.out.GetUserInfoOut;
import com.ztfgroup.supervise.entity.User;
import com.ztfgroup.supervise.service.impl.UserServiceImpl;
import com.ztfgroup.supervise.util.Constants;
import com.ztfgroup.supervise.wxparam.AccessTokenApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 实现原生拦截器的接口
 * 微信授权登录
 */
public class ZtWxInterceptor implements HandlerInterceptor {

    @Value("${supervise.corpid}")
    private String corpid;

    @Value("${supervise.corpsecret}")
    private String corpsecret;

    @Value("${supervise.errorurl}")
    private String errorurl;


    @Autowired
    private AccessTokenApi accessTokenApi;

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession();
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RequiredWxOauth2 annotation = method.getAnnotation(RequiredWxOauth2.class);
            try {
                if (annotation != null) {
                    String userId = (String) session.getAttribute(Constants.USER_ID);
                    if (!StringUtils.isEmpty(userId)) {
                        return true;
                    }
                    String code = request.getParameter("code");
                    if (StringUtils.isEmpty(userId) && !StringUtils.isEmpty(code)) {
                        String accessToken = accessTokenApi.getAccessToken(corpid, corpsecret);
                        GetUserInfoOut getUserInfoOut = SnsAPI.getUserInfo(accessToken, code);
                        if (Objects.equals(Constants.WX_SUCCESS_CODE, getUserInfoOut.getErrcode())) {
                            //获取微信用户ID
                            String wxUserId = getUserInfoOut.getUserId();
                            //查询对应用户表
                            User user = userServiceImpl.selectOne(new QueryWrapper<User>().eq("WX_USER_ID", wxUserId));
                            //若用户表中无该微信用户，则跳转错误页面
                            if (user == null) {
                                response.sendRedirect(errorurl);
                                return false;
                            }
                            session.setAttribute(Constants.USER_ID, user.getUserId());
                        }
                        return true;
                    }
                    String url = request.getRequestURL() + (request.getQueryString() == null ? "" : "?" + request.getQueryString());
                    if (StringUtils.isEmpty(userId)) {
                        String oauth2url = SnsAPI.connectOauth2Authorize(corpid, url, ScopeEnum.SNSAPI_BASE, "");
                        response.sendRedirect(oauth2url);
                        return false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

}
